<?php

namespace App\Http\Controllers\MiniApp;

use App\Enums\MiniAPP\TableReserveStatus;
use App\Helper\ApiResponseHelper;
use App\Http\Controllers\Controller;
use App\Http\Requests\MiniAPP\TableReserveRequest;
use App\Http\Resources\MiniAPP\TableReserveResource;
use App\Http\Resources\MiniAPP\TableTypeResource;
use App\Models\FakeTableReserve;
use App\Models\FakeTableType;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class TableController extends Controller
{
    public function getTypeList()
    {
        $types = FakeTableType::latest()->get();

        return TableTypeResource::collection($types);
    }

    public function getTypeInfo(FakeTableType $type)
    {
        return new TableTypeResource($type);
    }

    public function getCanReserve(FakeTableType $type, Request $request)
    {
        //获取日期
        $date = $request->date ?? now()->toDateString();

        //循环获取0到23点的时间
        $times = [];
        for ($i = 0; $i < 24; $i++) {

            $buf = [
                'time' => $i,
                'can_reserve' => true,
                'end_time' => $i + 1,
            ];

            if (FakeTableReserve::where([
                'fake_table_type_id' => $type->id,
                'date' => $date,
                'time' => $i,
            ])->exists()) {
                $buf['can_reserve'] = false;
            }

            $times[] = $buf;
        }

        return ApiResponseHelper::json($times);
    }

    public function reserve(FakeTableType $type, TableReserveRequest $request)
    {
        if (FakeTableReserve::where([
            'fake_table_type_id' => $type->id,
            'date' => $request->date,
            'time' => $request->time,
        ])->exists()) {
            return ApiResponseHelper::json([], 400, '该时间段已被预约');
        }

        $reserve = FakeTableReserve::create($request->only([
            'name', 'phone', 'people_count', 'need_assistant', 'date', 'time', 'store_id',
        ]) + [
            'fake_table_type_id' => $type->id,
                'member_id' => Auth::id(),
                'status' => TableReserveStatus::Pending,
            ]);

        return new TableReserveResource($reserve);
    }

    public function getReserveList(Request $request)
    {
        $reserves = FakeTableReserve::with([
            'tableType', 'member', 'store'
        ])->where('member_id', Auth::id())->latest();

        if (!empty($request->status)) {
            $reserves = $reserves->where('status', $request->status);
        }

        $reserves = $reserves->paginate();

        return TableReserveResource::collection($reserves);
    }
}
